﻿using ConsoleApp.Model.Dto;
using ConsoleApp.Model.Entity;
using ConsoleApp.Model.Option;
using ConsoleApp.Service;
using Furion;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace ConsoleApp.Controller
{
    [DynamicApiController]
    public class TestController
    {

        IHttpService _httpService;
        private IDbService _dbService;
        IConfiguration _configuration;
        private AutoDingContext _ctx;

        public TestController(IHttpService httpService, AutoDingContext ctx, IDbService dbService, IConfiguration configuration)
        {
            _ctx = ctx;
            _dbService = dbService;
            _configuration = configuration;
            _httpService = httpService;
        }

        public string Say()
        {
            return "Hello, Furion " + App.Configuration["Logging:LogLevel:Default"];
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<AjaxResult> doLogin(UserLoginDto param)
        {
            try
            {
                if (string.IsNullOrEmpty(param.Username) || string.IsNullOrEmpty(param.Password))
                {
                    throw new Exception("参数不能为空");
                }
                var jwtOpt = _configuration.GetSection("JwtOpt").Get<JwtOpt>();
                return _dbService.ValiDateUser(param, jwtOpt);
            }
            catch (Exception ex)
            {
                return AjaxResult.Error(ex.Message);
            }
        }
        


        public async Task<AjaxResult> doSign()
        {
            try
            {
                TimeSpan mTimeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
                long timestamp = (long)mTimeSpan.TotalSeconds * 1000;

                string dbUser = _ctx.Configs.Where(x => x.ConfigKey == "LOGIN_USER").FirstOrDefault().ConfigValue;
                string dbPassword = _ctx.Configs.Where(x => x.ConfigKey == "LOGIN_PWD").FirstOrDefault().ConfigValue;
                
                string username = DoEncrypt.getEnpcrypt(dbUser);
                string password = DoEncrypt.getEnpcrypt(dbPassword);
                string t = DoEncrypt.getEnpcrypt(timestamp.ToString());

                LoginModel loginParam = new LoginModel()
                {
                    phone = username,
                    password = password,
                    t = t
                };


                var infoRes = await _httpService.GetOrSaveTokenInfo(loginParam);

                double baseLog = 109.53496767736814; // 经度基准点  
                double baseLat = 24.401668705191504; // 维度基准点  
                double radius = 200; // 距离基准点的半径  

                string loga, lata;

                HelpFunc.GenerateRandomGps(baseLog, baseLat, radius, out loga, out lata);


                string description = "";
                string province = "";

                string city = "";
                string longitude = loga;
                string latitude = lata;
                string address = "广西壮族自治区 · 柳州市 · 鱼峰区 · 在柳州职业技术学院(官塘校区)附近";


                SignRes res1= await _httpService.tosign(description, address, province, city, longitude, latitude, t, infoRes.token, infoRes.planId, infoRes.userId);

                Log log = new Log();
                AjaxResult res2 = new AjaxResult();
                if (res1.code == 200)
                {
                    res2.code = 200;
                    res2.msg = "打卡成功";
                    log.Msg = "打卡成功";
                    log.CreateTime = DateTime.Now;
                }
                else
                {
                    string err = JsonConvert.SerializeObject(res1);
                    res2.code = 500;
                    res2.msg = $"打卡失败,接口响应为:{err}";
                    log.Msg = $"打卡失败,接口响应为:{err}";
                    log.CreateTime = DateTime.Now;
                }
            
                _ctx.Logs.Add(log);
                await _ctx.SaveChangesAsync();

                return res2;
            }
            catch (Exception ex)
            {
                Log log = new Log();
                log.Msg = $"打卡失败,错误信息{ex.Message}";
                log.CreateTime = DateTime.Now;
                _ctx.Logs.Add(log);
                await _ctx.SaveChangesAsync();
                return AjaxResult.Error(ex.Message);
            }
        }


    }
}
